/*
  $Id: popup_cart.js $
  TomatoCart Open Source Shopping Cart Solutions
  http://www.tomatocart.com

  Copyright (c) 2009 Wuxi Elootec Technology Co., Ltd

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License v2 (1991)
  as published by the Free Software Foundation.
*/

var PopupCart = new Class({
  Implements: [Options, Events],
  options: {
    remoteUrl: 'json.php',
    sessionName: 'sid',
    sessionId: null,
    triggerEl: $('popupCart'),
    container: $('pageHeader'),
    clsCollapsed: 'cartCallpased',
    clsExpanded: 'cartExpanded',
    clsCartText: 'cartText',
    clsItems: 'popupCartItems',
    relativeTop: 60,
    relativeLeft: -10,
    autoCloseDuration: 1000,
    movedPicSize: 2
  },
  
  /**
   * Initialize the popup cart object
   * 
   * @param options
   * 
   * return void
   */
  initialize: function(options) {
    this.setOptions(options);
    this.registerEvents();
    
    /**
     * Flag - verify whether the mouse is on the displayed cart.
     * In this case, the displayed cart shouldn't be closed automatically after the configured duration
     */
    this.mouseOnCartContainer = false;
    
    //Flag - verify whether the popup cart is expanded
    this.isCartExpanded = false;
    
    /**
     * Flag - verify whether the mouse is on the trigger of the popup cart.
     * In this case, the displayed cart shouldn't be closed automatically after the configured duration
     */
    this.mouseOnTrigger = false;
  },
  
  /**
   * register the mouseover events for the trigger element
   * 
   * return void
   */
  registerEvents: function() {
    this.options.triggerEl.addEvents({
      'mouseover': function() {
        //verify whether the cart is expanded
        if (this.isCartExpanded == false) {
        	this.isCartExpanded = true;
        	this.mouseOnTrigger = true;
        	
        	//get the html content of the popup cart with ajax request
          this.sendRequest({action: 'get_cart_contents'}, function(response) {
            this.displayCart(response);
          });
          
          //add the class for the cart text
          $$('.' + this.options.clsCartText).each(function(text) {
            if (text.hasClass(this.options.clsCollapsed)) {
              text.removeClass(this.options.clsCollapsed);
            }
            
            text.addClass(this.options.clsExpanded);
          }.bind(this));                
        }

        //close the popup cart automatically after the duration(3 seconds)
        this.autoClose.bind(this).delay(this.options.autoCloseDuration);

        return false;         
      }.bind(this),
      
      'mouseleave': function() {
      	this.mouseOnTrigger = false;

        //close the popup cart automatically after the duration(3 seconds)
        this.autoClose.bind(this).delay(this.options.autoCloseDuration);

        return false;
      }.bind(this)
    });
  },
  
  
  /**
   * close the popup cart automatically
   * 
   * return void
   */
  autoClose: function() {    
  	//verify whether the popupcart is expanded
    if (this.isCartExpanded == true) {
    	//if the mouse isn't on the cart container, it will be closed after the duration
      if ($defined(this.cartContainer) && this.mouseOnCartContainer == false && this.mouseOnTrigger == false) {
        this.cartContainer.fade('out');
        
        this.isCartExpanded = false;
        
        //add the class for the cart text
        $$('.' + this.options.clsCartText).each(function(text) {
          if (text.hasClass(this.options.clsExpanded)) {
            text.removeClass(this.options.clsExpanded);
          }
          
          text.addClass(this.options.clsCollapsed);
        }.bind(this));
      }
    }
  },
  
  /**
   * display the popup cart and register the events on it
   * 
   * @param response 
   * 
   * return void
   */
  displayCart: function(response) {
    var result = JSON.decode(response);

    //set the html content of the popup cart
    if (result.success == true) {
      if (!$defined(this.cartContainer)) {
        var pos = this.options.triggerEl.getCoordinates();
        
        this.cartContainer = new Element('div', {
          'html': result.content,
          'id': 'popupCartContent',
          'styles': {
            'position': 'absolute',
            'opacity': 0,
            'top': pos.top + this.options.relativeTop,
            'left': pos.left - this.options.relativeLeft    
          }
        });
      } else {
        this.cartContainer.set('html', result.content);
      }
      
      //fade in the popup cart
      this.options.container.adopt(this.cartContainer);
      this.cartContainer.fade('in');
      
      //hide the popup content as the mouse leave
      this.cartContainer.addEvent('mouseleave', function() {
        if ($defined(this.cartContainer)) {
          this.cartContainer.fade('out');
        }
        
        this.isCartExpanded = false;
        
        $$('.' + this.options.clsCartText).each(function(text) {
          if (text.hasClass(this.options.clsExpanded)) {
            text.removeClass(this.options.clsExpanded);
          }
          
          text.addClass(this.options.clsCollapsed);
        }.bind(this));
        
        this.mouseOnCartContainer = false;
      }.bind(this));
      
      //clear the autoclose timer as mouseover on the cart container
      this.cartContainer.addEvent('mouseover', function() {
        this.mouseOnCartContainer = true;
      }.bind(this));
    }
  },
    
  /**
   * send the ajax request
   * 
   * @param params - an object composed of the params which will be sent in the reqeust
   * @param callback - an function will be called after receiving the respose from the server
   * 
   * return void
   */
  sendRequest: function(params, callback) {
    var data = {
      template: this.options.template,
      module: 'popup_cart',
      method: 'post'
    };
    
    data[this.options.sessionName] = this.options.sessionId;
    
    $extend(data, params);
    
    //send the ajax request
    var loadRequest = new Request({
      url: this.options.remoteUrl,
      data: data,
      onSuccess: callback.bind(this)
    }).send();
  }
});